#include "wptitlebar.h"
#include "busyindicator.h"

#ifdef Q_WS_MAEMO_5
    #include <QDBusConnection>
    #include <QDBusMessage>
#endif

#include <QHBoxLayout>
#include <QSizePolicy>

WPTitleBar::WPTitleBar (QWidget *parent, const QString &title, BusyIndicator *busyIndicator) :
    QFrame(parent),
    iBusyIndicator(busyIndicator)
{
    // layout
    QHBoxLayout *layout = new QHBoxLayout();

    layout->setSpacing(0);
    layout->setContentsMargins(0, 0, 0, 0);

    // widgets
    iTitle = new QLabel(title);
    iSpinner = new QPushButton();
    iSpinner->setObjectName("WPTitleBarSpinner");
    iSpinner->setFocusPolicy(Qt::NoFocus);

#ifdef Q_WS_MAEMO_5
    // button with only pixmap
    iExposeButton = new QPushButton(QPixmap(":/images/menu_icon.png"), QString());

    connect(iExposeButton, SIGNAL(clicked()), this, SLOT(showExpose()));
    
    iExposeButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred);
    iExposeButton->setFocusPolicy(Qt::NoFocus);
    layout->addWidget(iExposeButton);
#endif

    // we need to be really careful about our layout
    iSpinner->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred);
    iTitle->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred);    // expand

    layout->addWidget(iTitle);
    layout->addWidget(iSpinner);

    // update spinner 
    connect(iBusyIndicator, SIGNAL(changed()), this, SLOT(updateSpinner()));
    connect(iSpinner, SIGNAL(clicked()), this, SIGNAL(spinnerClicked()));

    setLayout(layout);

    // expand horizontally, fixed height
    setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
}
    
void WPTitleBar::setText (const QString &title)
{
    iTitle->setText(title);
}

void WPTitleBar::updateSpinner ()
{
    if (iBusyIndicator->IsActive()) {
        iSpinner->show();
        iSpinner->setIcon(iBusyIndicator->PixmapToDraw());

    } else {
        iSpinner->hide();
    }
}

#ifdef Q_WS_MAEMO_5
void WPTitleBar::showExpose ()
{
    QDBusConnection connection = QDBusConnection::sessionBus();
    QDBusMessage message = QDBusMessage::createSignal("/", "com.nokia.hildon_desktop", "exit_app_view");

    connection.send(message);
}
#endif

